package com.zzy.mccjt.service.service.impl;


import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.zzy.mccjt.entity.system.SystemUser;
import com.zzy.mccjt.pojo.common.CurrentUser;
import com.zzy.mccjt.pojo.common.TokenProperties;
import com.zzy.mccjt.service.common.framework.response.WebApiResponse;
import com.zzy.mccjt.service.common.util.JwtUtil;
import com.zzy.mccjt.service.dao.UserMapper;
import com.zzy.mccjt.service.service.LoginService;
import com.zzy.pojo.system.login.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenProperties tokenProperties;


    @Override
    public WebApiResponse<String> logIn(UserDTO u) {
        SystemUser user = new SystemUser();
        user.setUsername(u.getUsername());
        user.setPassword(Base64.encode(u.getPassword()));
        user = userMapper.selectOne(user);
        if (null == user){
            return WebApiResponse.error("用户名或密码错误");
        }
        CurrentUser currentUser = new CurrentUser(user.getId(),user.getUsername());
        TokenProperties.JwtProperties jwtProperties=tokenProperties.getSystem();
        String jwtToken = JwtUtil.createJWT(jwtProperties.getIssuer(), JSON.toJSONString(currentUser),jwtProperties.getBase64Security(),jwtProperties.getExpiration());
        log.debug("jwtToken生成成功，name：{}, token: {}", user.getUsername(), jwtToken);
        return WebApiResponse.success(jwtToken);
    }


    @Override
    public WebApiResponse<String> regist(UserDTO u) {
        SystemUser user = new SystemUser();
        user.setUsername(u.getUsername());
        user = userMapper.selectOne(user);
        if (null != user){
            return WebApiResponse.error("用户名已存在");
        }
        user = new SystemUser();
        user.setUsername(u.getUsername());
        user.setPassword(Base64.encode(u.getPassword()));
        userMapper.insertSelective(user);
        return WebApiResponse.success();
    }

}


